package com.zerosoft.guotai.thread;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class OnlineThreadFactory implements ThreadFactory {
    /**
     * 自增线程序号
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * 线程名称前缀
     */
    private final String threadNamePrefix;

    /**
     * 构造方法
     * @param threadNamePrefix 方法前缀
     */
    public OnlineThreadFactory(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix.concat(StrUtil.DASHED);
    }


    /**
     * Constructs a new unstarted {@code Thread} to run the given runnable.
     *
     * @param runnable a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     * create a thread is rejected
     * @see <a href="../../lang/Thread.html#inheritance">Inheritance when
     * creating threads</a>
     */
    @Override
    public Thread newThread(Runnable runnable) {
        // 设置线程池名称
        Thread thread = new Thread(runnable , threadNamePrefix.concat(StrUtil.toString(threadNumber.getAndIncrement())));

        // 设置守护线程
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        // 同意设置程默认优先级 5
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
